    package com.example.springboot.controller;

    import com.example.springboot.entity.User;
    import com.example.springboot.service.OSSService;
    import com.example.springboot.service.UserService;
    import com.example.springboot.config.JwtTokenUtil;
    import com.github.pagehelper.Page;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;

    import javax.servlet.http.HttpServletRequest;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    @RestController
    @RequestMapping("/users")
    public class UserController {

        @Autowired
        private UserService userService;
        @Autowired
        private OSSService ossService;
        @Autowired
        private JwtTokenUtil jwtTokenUtil;


        @Autowired
        private HttpServletRequest request; // 用于访问请求属性，由过滤器设置

        private static final Logger logger = LoggerFactory.getLogger(UserController.class);



        @PutMapping("/update/username/{userId}")
        public Map<String, Object> updateUsername(@PathVariable Integer userId, @RequestBody String username) {
            String tokenRealUserId = (String) request.getAttribute("realUserId");
            System.out.println("Token RealUserId: " + tokenRealUserId + ", Path UserId: " + userId);

            if (tokenRealUserId == null || !tokenRealUserId.equals(String.valueOf(userId))) {
                throw new RuntimeException("无权限：当前用户无法修改其他用户的用户名");
            }

            userService.updateUsername(userId, username);

            // 生成新的 token
            String tokenUsername = (String) request.getAttribute("username");
            String role = (String) request.getAttribute("role");
            String newToken;
            if ("USER".equalsIgnoreCase(role)) {
                // 用户角色使用包含 realUserId 的 token
                newToken = jwtTokenUtil.generateToken(tokenUsername, role, tokenRealUserId);
            } else {
                // 其他角色（管理员、商家）使用原有方法
                newToken = jwtTokenUtil.generateToken(tokenUsername, role);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("message", "用户名更新成功");
            response.put("token", newToken);
            return response;
        }

        @PostMapping("/update/avatar/{userId}")
        public Map<String, Object> updateAvatar(@PathVariable Integer userId, @RequestParam("file") MultipartFile file) {
            String tokenRealUserId = (String) request.getAttribute("realUserId");
            System.out.println("Token RealUserId: " + tokenRealUserId + ", Path UserId: " + userId);

            if (tokenRealUserId == null || !tokenRealUserId.equals(String.valueOf(userId))) {
                throw new RuntimeException("无权限：当前用户无法修改其他用户的头像");
            }

            try {
                String avatarUrl = ossService.uploadImage(file);
                userService.updateAvatar(userId, avatarUrl);

                Map<String, Object> response = new HashMap<>();
                response.put("message", "头像更新成功");
                response.put("avatarUrl", avatarUrl);
                return response;
            } catch (Exception e) {
                throw new RuntimeException("头像上传失败: " + e.getMessage());
            }
        }

        // 获取用户列表（分页，仅限超级管理员）
        @GetMapping("/list")
        public ResponseEntity<Page<User>> getUserList(
                @RequestParam(defaultValue = "1") int page,
                @RequestParam(defaultValue = "10") int size,
                @RequestParam(required = false) String query,
                HttpServletRequest request) {
            String username = (String) request.getAttribute("username");
            Page<User> users = userService.getAllUsers(username, page, size, query);
            if (users == null) {
                logger.warn("用户 {} 无超级管理员权限，无法获取用户列表", username);
                return ResponseEntity.status(403).body(null);
            }
            return ResponseEntity.ok(users);
        }

        // 删除用户（仅限超级管理员）
        @DeleteMapping("/delete/{userId}")
        public ResponseEntity<String> deleteUser(
                @PathVariable Integer userId,
                HttpServletRequest request) {
            String username = (String) request.getAttribute("username");
            boolean success = userService.deleteUser(userId, username);
            if (!success) {
                logger.warn("用户 {} 无超级管理员权限，无法删除用户 ID: {}", username, userId);
                return ResponseEntity.status(403).body("无权限删除用户");
            }
            return ResponseEntity.ok("用户删除成功");
        }

        // 新增用户（仅限超级管理员）
        @PostMapping("/add")
        public ResponseEntity<String> addUser(
                @RequestBody User user,
                HttpServletRequest request) {
            String username = (String) request.getAttribute("username");
            boolean success = userService.addUser(user, username);
            if (!success) {
                logger.warn("用户 {} 无超级管理员权限，无法添加用户", username);
                return ResponseEntity.status(403).body("无权限添加用户");
            }
            return ResponseEntity.ok("用户添加成功");
        }

        // 更新用户（仅限超级管理员）
        @PutMapping("/update/{userId}")
        public ResponseEntity<String> updateUser(
                @PathVariable Integer userId,
                @RequestBody User user,
                HttpServletRequest request) {
            String username = (String) request.getAttribute("username");
            boolean success = userService.updateUser(userId, user, username);
            if (!success) {
                logger.warn("用户 {} 无超级管理员权限，无法更新用户 ID: {}", username, userId);
                return ResponseEntity.status(403).body("无权限更新用户");
            }
            return ResponseEntity.ok("用户更新成功");
        }

        // 获取单个用户信息（仅限超级管理员）
        @GetMapping("/{userId}")
        public ResponseEntity<User> getUserById(
                @PathVariable Integer userId,
                HttpServletRequest request) {
            String username = (String) request.getAttribute("username");
            User user = userService.getUserById(userId, username);
            if (user == null) {
                logger.warn("用户 {} 无超级管理员权限，或用户 ID: {} 不存在", username, userId);
                return ResponseEntity.status(403).body(null);
            }
            return ResponseEntity.ok(user);
        }
    }
